# -*- coding: UTF-8 -*-
"""
@Project :xlx-fastapi
@File    :admin_identity_token.py
@Author  :xlx-ali
@Date    :2024/06/24 15:03 星期一
"""
import time

from app import dao
from app.types import apiproto
from app.utils.str_util import StringUtil


class AdminIdentityTokenService:
    """TOKEN管理"""

    @classmethod
    def makeToken(cls, adminId, token):
        """
        生成 token

        Args:
            admin_id (int): 管理员ID
            token (str): TOKEN
        Returns:
            str: 生成的token字符串

        Author:
            edc
        """
        expire = int(StringUtil.webConfig('token_expire'))
        if expire >= 10:
            expire = expire * 60
        else:
            # 默认7天有效期
            expire = 604800
        token = StringUtil.GenerateMd5(token)
        tokenAdminId = dao.AdminIdentityTokenQueryDao.findByAdminId(adminId)
        if not tokenAdminId:
            insertData = apiproto.AdminIdentityTokenDetailProto(admin_id=adminId, token=token, expire=expire,
                                                                updatetime=int(time.time()))

            return dao.AdminIdentityTokenOperateDao.insertGetId(insertData)
        updateData = {'token': token, 'updatetime': int(time.time()), 'expire': expire}
        dao.AdminIdentityTokenOperateDao.updateByAdminId(adminId, **updateData)

    @classmethod
    def refreshToken(cls, adminId):
        """
        刷新 token

        Args:
            admin_id (int): 管理员ID
        Returns:
            bool: 是否刷新成功

        Author:
            edc
        """
        info = dao.AdminIdentityTokenQueryDao.findByAdminId(adminId)
        if not info or (info.updatetime + info.expire) < int(time.time()):
            dao.AdminIdentityTokenOperateDao.delByAdminId(adminId)
            return False
        updateData = {'updatetime': int(time.time())}
        dao.AdminIdentityTokenOperateDao.updateByAdminId(adminId, updateData)
        return True
